package com.tangji.signaltower.runners;

import com.tangji.signaltower.runners.client.ForexPoNettyClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.websocket.ContainerProvider;
import javax.websocket.DeploymentException;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;
import java.io.IOException;
import java.net.URI;

/**
 * Created with IntelliJ IDEA.
 * User: yujianfu (mr.vencnet@gmail.com)
 * Date: 2020-07-04
 * Time: 01:25
 */
//@Component
public class SocketClientRunner implements CommandLineRunner {
    private static Logger logger = LoggerFactory.getLogger(SocketClientRunner.class);

    public static Thread getDataThread;

    @Override
    public void run(String... strings) {
        getData();
    }


    private void getData() {
        getDataThread = new Thread(() -> {
            try {
                logger.info("== SocketClientRunner 开始订阅 ==");
//                WebSocketContainer container = ContainerProvider.getWebSocketContainer();
//                URI apiUri = URI.create("wss://ws.binaryws.com/websockets/v3?app_id=28054");
//                Session session = container.connectToServer(WSClient.class, apiUri);
//                while (session.isOpen()) {
//                    // receive ticks
//                }
                ForexPoNettyClient.getInst().startConnectServerAlways(System.currentTimeMillis() + "");
            } catch (Exception e) {
                logger.error("== SocketClientRunner 异常1 ==", e);
                e.printStackTrace();
            }
        });
        getDataThread.start();
    }


    private void getActiveSymbols() {
        new Thread(() -> {
            try {
                WebSocketContainer container = ContainerProvider.getWebSocketContainer();
                URI apiUri = URI.create("wss://ws.binaryws.com/websockets/v3?app_id=28054");
                Session session = container.connectToServer(ActiveSymbols.class, apiUri);
                while (session.isOpen()) {
                    // receive ticks
                }
            } catch (DeploymentException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }


    public static void main(String[] args) {
        logger.info("== SocketClientRunner 开始订阅 ==");
        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        URI apiUri = URI.create("wss://ws.binaryws.com/websockets/v3?app_id=28054");
        try {
            Session session = container.connectToServer(WSClient.class, apiUri);
            while (session.isOpen()) {
                // receive ticks
            }
        } catch (DeploymentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
